set -e

KAEP_ROOT_DIR=$(cd $(dirname $0)/; pwd)
echo $KAEP_ROOT_DIR

BUILD_TYPE="Debug"
ENABLE_ASAN="OFF"
OPENHITLS_DIR="platform/openhitls"
SECURE_C_DIR="platform/openhitls/platform/Secure_C"
CUSTOM_CFLAGS=""

echo "准备全新构建环境..."
rm -rf "${KAEP_ROOT_DIR}/build"
mkdir -p "${KAEP_ROOT_DIR}/build"
cd "${KAEP_ROOT_DIR}/build" || exit

build_depend_code()
{
    # 构建Secure_C
    echo "构建Secure_C..."
    if [ ! -f "${KAEP_ROOT_DIR}/${SECURE_C_DIR}/libboundscheck.a" ]; then
        cd "${KAEP_ROOT_DIR}/${SECURE_C_DIR}"
        make -j$(nproc)
        cd -
    fi

    # 构建OpenHiTLS
    echo "构建OpenHiTLS..."
    if [ ! -d "${KAEP_ROOT_DIR}/platform/openhitls/build" ]; then
        mkdir -p ${KAEP_ROOT_DIR}/platform/openhitls/build
        cd ${KAEP_ROOT_DIR}/platform/openhitls/testcode/script
        bash build_hitls.sh
        cd -
    fi
}

# 下载依赖
echo "检查依赖项..."
if [ ! -d "${KAEP_ROOT_DIR}/${OPENHITLS_DIR}" ]; then
    echo "下载OpenHiTLS..."
    mkdir -p "${KAEP_ROOT_DIR}/platform"  # 确保父目录存在
    git clone --recurse-submodules https://gitcode.com/openhitls/openhitls.git "${KAEP_ROOT_DIR}/${OPENHITLS_DIR}"
    cd ${KAEP_ROOT_DIR}/platform/openhitls
    git reset --hard d41736634e8ce4d610fb49ccee2e86f1903bd4d6
    cd -
fi

build_depend_code

if [ -f ${KAEP_ROOT_DIR}/${OPENHITLS_DIR}/build/macro.txt ]; then
    CUSTOM_CFLAGS=$(cat ${KAEP_ROOT_DIR}/${OPENHITLS_DIR}/build/macro.txt)
    CUSTOM_CFLAGS="$CUSTOM_CFLAGS -D__FILENAME__=__FILE__"
fi

# 运行CMake配置
echo "生成构建系统..."
cmake .. \
    -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \
    -DENABLE_ASAN=${ENABLE_ASAN} \
    -DCMAKE_PREFIX_PATH="${KAEP_ROOT_DIR}/${OPENHITLS_DIR};${KAEP_ROOT_DIR}/${SECURE_C_DIR}" \
    -DCUSTOM_CFLAGS="${CUSTOM_CFLAGS}" \
    -DWD_DIR=/usr/local/include/warpdrive

# 编译项目
echo "开始编译..."
make -j$(nproc)

echo "构建完成!"
